import router from './router'
import store from './store'

const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
	// 判断token
	const userMsg =
		JSON.parse(window.localStorage.getItem('userMsg')) || store.getters.userMsg
	const token = userMsg ? userMsg.token : ''
	if (token) {
		if (to.path == '/login') {
			next({ path: '/' })
		} else {
			if (!store.getters.addRoutes.length && !store.getters.hasgetRoutes) {
				let res = await store.dispatch('router/ADD_ROUTES')
				if (res.length > 0) {
					res.forEach(i => {
						router.addRoute(i)
					})
				}
				store.commit('common/CHANGE_SIDEMENULIST', res)
				next({ path: to.path })
			} else {
				next()
			}
		}
	} else {
		if (whiteList.indexOf(to.path) !== -1) {
			next()
		} else {
			store.commit('user/CLEAR_USERMSG')
			store.commit('router/CLEAR_ADDROUTES')
			next(`/login?redirect=${to.path}`)
		}
	}
})
